
/*

示例描述:
    1-启动服务监听: http://localhost:3000
        1-1 监听路由:  /api/list   (GET请求)
        1-2 监听路由:  /api/create (POST请求)
        1-3 其它路由返回 404
 */
const http = require('http')
const querystring = require('querystring')

const server = http.createServer((req, res) => {

    const url = req.url
    const path = url.split('?')[0]
    const queryStr = url.split('?')[1]
    const method = req.method
    const query = querystring.parse(queryStr) //将queryStr转为对象
    console.log('query = ',query)
    console.log('url = ',url)
    console.log('path = ',path)

    // 定义路由1
    if (path === '/api/list' && method === 'GET') {
        const result = {
            errno: 0,
            data: [
                {user: '张三', content: '留言1'},
                {user: '李四', content: '留言2'}
            ]
        }
        res.writeHead(200, {'Content-type': 'application/json'})
        res.end(JSON.stringify(result))
        return;
    }

    // 定义路由2
    if (path === '/api/create' && method === 'POST') {
        const reqType = req.headers['content-type']
        let bodyStr = ''

        // 监听数据传输  chunk 即“流”的每一段数据
        req.on('data', chunk => {
            bodyStr = bodyStr + chunk.toString()
        })

        // 监听数据传输完成
        req.on('end', () => {
            if (reqType === 'application/json') { // json 格式
                const body = JSON.parse(bodyStr)
                console.log('body is ', body) // 对象格式
            }
            res.end('接收完成') // 异步
        })

        const result = {
            errno: 0,
            message: '创建成功'
        }
        res.writeHead(200, { 'Content-type': 'application/json' })
        res.end( JSON.stringify(result) ) // body
        return
    }

    // 其它路由3
    res.writeHead(404, {'Content-type': 'text/html'})
    res.end(`
        <!DOCTYPE html>
        <html lang="zh">
            <head>
                <title>404</title>
            </head>
            <body>
                <h1>404 Not Found</h1>
            </body>
        </html>
    `)
})

server.listen(3000) // 可以监听 http 请求
console.log('http 请求已经被监听;请访问 http://localhost:3000')
